<template>
  <div name="sysInfoManagement" class="sysInfoManagement">
    <el-form :inline="true" :model="searchForm">
      <!--搜索框-->
      <el-form-item>
        <el-input
            v-model="searchForm.params.id"
            placeholder="接收者id或发送者id"
            clearable>
        </el-input>
      </el-form-item>


      <el-form-item>
        <el-button @click="getListInfo">搜索</el-button>
        <el-button type="primary" @click="dialogFormVisible = true" >新增</el-button>
        <!--确认按钮-->
        <el-popconfirm title="确定要删除这些记录吗？"
                       @confirm="delHandle(null)"
                       style="margin-left: 10px;">
          <el-button type="danger"
                     slot="reference"
                     :disabled="delBtnStu">批量删除</el-button>
        </el-popconfirm>

      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        border
        stripe
        :data="ListInfo"
        tooltip-effect="dark"
        style="width: 85%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="id"
          label="信息id"
          width="75">
      </el-table-column>
      <el-table-column
          prop="sender"
          label="发送者id"
          width="80">
      </el-table-column>
      <el-table-column
          prop="receiver"
          label="接收者id"
          width="100">
      </el-table-column>

      <el-table-column
          prop="infoName"
          label="信息类型"
          width="110">
      </el-table-column>

      <el-table-column
          prop="isRead"
          label="已读状态"
          width="80">
        <template slot-scope="scope">
          {{changeIsRead(scope.row.isRead)}}
        </template>
      </el-table-column>

      <el-table-column
          prop="createTime"
          label="发送日期"
          width="100">
        <template slot-scope="scope">
          {{timeChange(scope.row.createTime)}}
        </template>
      </el-table-column>

      <el-table-column
          label="文本信息"
          width="100">
        <el-button
            slot-scope="scope"
            @click="showMoreInfo(scope.row)">
          查看
        </el-button>
      </el-table-column>

      <el-table-column
          width="150px"
          label="操作">
        <template slot-scope="scope">
          <el-button type="text"
                     @click="editHandle(scope.row.id)"
          >编辑</el-button>

          <el-divider direction="vertical"></el-divider>

          <el-popconfirm title="确定要删除这条记录吗？"
                         @confirm="delHandle(scope.row.id)">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>


    <!--其他信息弹出框-->
    <el-dialog :visible.sync="showMoreInfoDig">

      <el-descriptions
          title="文本信息"
          :column="1"
          border
          direction="vertical">

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            文本信息
          </template>
          {{moreInfo.content}}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!--编辑弹窗-->
    <el-dialog title="系统信息"
               :visible.sync="dialogFormVisible"
               width="600px"
               @closed="resetForm('editForm')">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editForm">
        <el-form-item label="发送者id" prop="sender" label-width="100px">
          <el-input v-model="editForm.sender"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="接收者id" prop="receiver" label-width="100px">
          <el-input v-model="editForm.receiver"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="信息类型" prop="infoType" label-width="100px">
          <el-select v-model="editForm.infoType">
            <el-option v-for="item in infoTypeList"
                       :key="item.id"
                       :label="item.type"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="已读状态" prop="isRead" label-width="100px">
          <el-select v-model = "editForm.isRead">
            <el-option v-for="item in isReadOption"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="创建时间" prop="birthday" label-width="100px">-->
        <!--  <el-date-picker style="width: 180px;"-->
        <!--                  v-model="editForm.createTime"-->
        <!--                  type="datetime"-->
        <!--                  format="yyyy-MM-dd"-->
        <!--                  value-format="yyyy-MM-dd"-->
        <!--                  placeholder="创建时间">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
        <el-form-item label="文本信息" prop="content" label-width="100px">
          <el-input v-model="editForm.content" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click.native="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "sysInfoManagement",
  data(){

    let validateReceiver = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('绑定的用户账号'));
      }
      let regex = /^\d{5,}$/;
      if(!regex.test(value)){
        callback(new Error('非合法账号格式'));
      }
      callback();
    };

    let validateSender = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('绑定的用户账号'));
      }
      let regex = /^\d{5,}$/;
      if(!regex.test(value)){
        callback(new Error('非合法账号格式'));
      }
      callback();
    };

    let validateInfoType = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('选择信息类型'));
      }
      callback();
    };

    let validateIsRead = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('选择已读状态'));
      }
      callback();
    }

    return{
      //更多消息窗
      showMoreInfoDig: false,
      //删除键
      delBtnStu: true,
      //编辑窗
      dialogFormVisible: false,

      //搜索对象
      searchForm: {
        data: '',
        method: "all-page",
        params: {
          current: this.current,
          id: 0,
          size: this.size
        }
      },
      //
      ListInfo: [
        {
          id: 0,
          sender: 0,
          receiver: 0,
          content: '',
          infoType: 0,
          createTime: 0,
          isRead: false,
          infoName: ''
        }
      ],
      //
      isReadOption:[
        {
          value: true,
          label: '已读'
        },
        {
          value: false,
          label: '未读'
        }
      ],

      //文本显示
      moreInfo:{
        content: ''
      },
      infoTypeList: [
        {
          id: 0,
          type: ''
        }
      ],

      //编辑窗口数据
      editForm: {
        id: 0,
        sender: 0,
        receiver: 0,
        content: '',
        infoType: 0,
        createTime: 0,
        isRead: false,
      },

      editFormRules: {
        sender: [
          {required: true,validator: validateSender , trigger: 'blur'}
        ],

        receiver: [
          {required: true,validator: validateReceiver , trigger: 'blur'}
        ],

        infoType: [
          {required: true,validator: validateInfoType, trigger: 'blur'}
        ],

        isRead: [
          {required: true,validator: validateIsRead, trigger: 'blur'}
        ]
      },

      current: 1,
      total: 0,
      size: 10,

    }
  },
  created() {
    this.getListInfo();
    this.getTypeInfo();
  }
  ,methods: {
    getListInfo(){
      const self = this;

      let choice = (this.searchForm.params.id !== 0 && this.searchForm.params.id !== '');

      let json = {
        method: choice ? 'userId-page' : 'all-page' ,
        params: {
          id: choice ? this.searchForm.params.id : 'null',
          'current': self.current,
          'size': self.size
        }
      }

      self.$axios.post('api/sysInfo/findSysInfo',json)
          .then(res=>{
            self.ListInfo = res.data.data.data;
            self.current = res.data.data.currentPage;
            self.size = res.data.data.size;
            self.total = res.data.data.total;
          }).catch(err => {
            console.log(err)
      })

    },
    getTypeInfo(){
      const self =this;
      this.$axios.get('api/sysInfo/accessInfoType')
          .then(res=>{
            self.infoTypeList = res.data.data;
          })
          .catch(err => {
            console.log(err);
      })
    },

    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.id)
      })
      console.log(ids)
      let url = 'api/sysInfo/deleteSysInfo'


      this.$axios.post(url, {'ids': ids}).then(res => {



        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getListInfo()
          }
        });
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    editHandle(id){
      console.log(id)
      let json = {
        sysInfoId: id,
      }
      this.$axios.post("api/sysInfo/selectSysInfoById",json).then(res => {
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })

    },
    //换显示数
    handleSizeChange(val) {
      this.size = val
      this.getListInfo()
    },
    //换页
    handleCurrentChange(val) {
      this.current = val
      this.getListInfo()
    },
    //重置弹出表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.dialogFormVisible = false
      this.permDialogFormVisible = false
    },
    //提交编辑
    submitEditForm(formName){
      console.log(this.editForm.id);

      let choice = (Number(this.editForm.id) !== 0
          && this.editForm.id !== undefined
          && String(this.editForm.id) !== '');

      this.$refs[formName].validate((valid) => {
        console.log("edit")
        if (valid) {
          this.$axios.post('api/sysInfo/' + ( choice
              ? "modifySysInfo"
              : "addSysInfo") ,this.editForm)
              .then(res => {
                console.log(res.data)
                this.resetForm(formName)
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getListInfo()
                  }
                });
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //将已读状态转化显示
    changeIsRead(val){
      return val === true
          ? '已读'
          : '未读';
    },

    showMoreInfo(val){
      const self = this;
      self.moreInfo.content = val.content;
      self.showMoreInfoDig = true;

    },
    timeChange(val){
      let str = val.toString();
      str = str.substring(0,19).replace('T',' ');

      return str;

    },
    textChange(val){
      if(val === null){
        return '暂无信息';
      }
      return val;
    }

  }
}
</script>

<style scoped>
  .sysInfoManagement{
    margin: 15px 15px;
  }
  .el-pagination{
    margin: 0 auto; text-align: center;
    /*margin-top: 22px;*/
  }
</style>